﻿using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;

public class ItemEnchantScene : Scene
{
    const int RareMax = 6;

    float gap = 60.0f;
    
    [NonSerialized]
    static MemberModel m_SelectMember;
    [NonSerialized]
    static Item m_SelectItem;

    int m_ItemPos = 0;

    public UISprite m_ItemBG;

    public Animation m_IntroAni; 
    public Animation m_SuccessAni;
    public Animation m_FailAni;

    public GameObject m_01Panel;
    public GameObject m_02Panel;
    public GameObject m_04Panel;

    public GameObject m_GreenEffect;
    public GameObject m_RedEffect;

    public UISprite m_GreenGage;
    public UISprite m_RedGage;

    public GameObject m_EffectIng;
    public GameObject m_EffectSuccess;

    public Collider m_Button_PowerUp;

    #region text설정
    public UILabel m_ItemName;
    public UILabel m_ItemLevel;

    public UILabel m_Name01;
    public UILabel m_CrrValue01;
    public UILabel m_UpValue01;

    public UILabel m_Name02;
    public UILabel m_CrrValue02;
    public UILabel m_UpValue02;

    public GameObject m_Text01Root;
    public GameObject m_Text02Root;

    public UILabel m_SuccessPercent;
    public UILabel m_SpendKina;

    public GameObject[] m_Stars_01;

    //success panel text
    public UILabel m_SuccessName01;
    public UILabel m_SuccessCrrValue01;   

    public UILabel m_SuccessName02;
    public UILabel m_SuccessCrrValue02;   

    //04panel

    public UILabel m_ItemName_04;
    public GameObject[] m_Stars_04;
    #endregion

    public Transform ItemRoot;

    bool m_IsGageMoving = false;

    bool m_IsFirstInit = true;

    int m_ParticleStartPosx = -225;
    int m_ParticleEndPosx = 388;
    int m_GageStartDimensionsX = 40;

    Vector3 m_02PanelOrizinPos = new Vector3(46, -30, 0);
    Vector3 m_02PanelFarPos = new Vector3(-10000, -10000, 10000);
    
    public override void AwakeScene()
    {
        if (UserData.Instance.userModel == null)
        {
            LoadingScene.TestInit();
            /**/
            //NetworkManager.Instance.C2S_LOGIN(AuthPlatformID.None, "hshshs", string.Empty, OnLoginCallback, OnLoginErrCallback);

            NetworkManager.Instance.C2S_GSTAR_JOIN(OnLoginCallback, OnLoginErrCallback);
        }
        /////////////////////////////////////////////////////////////////
        else
        {
            InitScene();
        }
    }

    void OnLoginErrCallback(ResponseModel<UserModel> recvData)
    {
        Debug.LogError("OnLoginErrCallback");
    }

    void OnLoginCallback(ResponseModel<UserModel> userData)
    {
        UserData.Instance.userModel = userData.data;
        SetMemberAndItem(null, UserData.Instance.userModel.inventory[0]);

        InitScene();
    }

    public override void StartScene()
    {
    }

    public override void UpdateScene()
    {
        UpdateGage();
    }

    public static void SetMemberAndItem(MemberModel selectModel, Item selectItem)
    {
        m_SelectMember = selectModel;
        m_SelectItem = selectItem;
    }

    public override void ButtonTouch(Collider collider)  // 버튼 터치 (터치 시작 끝 같은 오브젝트일때 터치 끝 시점에 호출)
    {
        switch(collider.name)
        {
            case "Button_PowerUp":
                {
                    m_Button_PowerUp.enabled = false;

                    if(m_SelectMember != null)      //장착된 아이템
                    {
                        m_ItemPos = 1;  //(mNo가 0일때 1-오른쪽, 2-왼쪽)
                        if (m_SelectMember.leftItem == m_SelectItem)
                            m_ItemPos = 2;

                        NetworkManager.Instance.C2S_ITEM_STRE(m_ItemPos, m_SelectMember.no, OnStrengtheningCallback);
                    }
                    else                            //인벤토리 아이템
                    {         
                        m_ItemPos = UserData.Instance.userModel.inventory.IndexOf(m_SelectItem);

                        NetworkManager.Instance.C2S_ITEM_STRE(m_ItemPos, 0, OnStrengtheningCallback);                      
                    }
                }
                break;
            case "Button_Back":
                {
                    BackButton();
                }
                break;
        }
    }

    void OnStrengtheningCallback(ResponseModel<UserModel> data)
    {
        m_Button_PowerUp.enabled = true;

        if(data.ecode == 0)
        {
            UserData.Instance.userModel = data.data;

            if (m_SelectMember != null)
            {
                m_SelectMember = UserData.Instance.userModel.members_dic[m_SelectMember.no.ToString()];

                if(m_ItemPos == 1)        
                    m_SelectItem = m_SelectMember.rightItem;
                else
                    m_SelectItem = m_SelectMember.leftItem;
            }
            else
            {
                m_SelectItem = UserData.Instance.userModel.inventory[m_ItemPos];
            }
           
            StartGageMove(true);

            if (data.responseResult.completeIdList.Count != 0)
            {
                foreach (int id in data.responseResult.completeIdList)
                {                   
                    ToastManager.Instance.ShowAchievementCompleteToast(id, true);
                }
            }
        }
        else if (data.ecode == -5511)       // 강화 실패
        {
            StartGageMove(false);

            if (data.responseResult.completeIdList.Count != 0)
            {
                foreach (int id in data.responseResult.completeIdList)
                {
                    ToastManager.Instance.ShowAchievementCompleteToast(id, true);
                }
            }
        }
        else if (data.ecode == -5506)       // 강화 실패 (max 레벨 초과)
        {
            Popup_OneButton popupSc = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;            

            popupSc.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId("uiItemUpgradeMax"));
        }  
        else
        {
            Popup_OneButton popupSc = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;

            string errorId = string.Format("systemErrorText{0}", Math.Abs(data.ecode));

            popupSc.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId(errorId));
        }  
    }

    void GetQuestInfo()
    {
        NetworkManager.Instance.C2S_GET_QUESTINFO(QuestManager.instance.ResponseGetQuestInfo);
    }

    void StartGageMove(bool isSuccess)
    {             
        m_01Panel.SetActive(false);
        //m_02Panel.SetActive(true);

        m_02Panel.transform.localPosition = m_02PanelOrizinPos;

        m_IntroAni.Play("Item_powerup_UI Up");

        StartCoroutine(GageMove(isSuccess));
    }

    IEnumerator GageMove(bool isSuccess)
    {
        yield return new WaitForSeconds(1.0f);
      
        System.Random rand = new System.Random();

        float aniTime = 4.0f;
        float EndAniTime = 0.2f;
        int max = m_ParticleEndPosx - m_ParticleStartPosx;

        int step = 20;
        //-225   ~  388
        int moveMax = max / (step + 1);
        int moveMin = (int)((float)moveMax * 0.3f);

        Vector3[] pos1 = new Vector3[step];
        Vector3[] pos2 = new Vector3[step];


        float y1 = 35.0f;
        float y2 = -37.0f;
        if (!isSuccess)
        {
            y2 = 35.0f;
            y1 = -37.0f;
        }

        int randNum1 = 0;
        int randNum2 = 0;

        pos1[0].Set(m_ParticleStartPosx, y1, 2.0f);
        pos2[0].Set(m_ParticleStartPosx, y2, 2.0f);

        for (int i = 1; i < step; i++)
        {
            randNum1 = rand.Next(moveMin, moveMax);
            randNum2 = rand.Next(moveMin, moveMax);

            pos1[i].Set(pos1[i - 1].x + (float)randNum1, y1, 2.0f);
            pos2[i].Set(pos2[i - 1].x + (float)randNum2, y2, 2.0f);
        }

        SetGageInit();

        if (isSuccess)
        {
            iTween.MoveTo(m_GreenEffect, iTween.Hash("islocal", true, "movetopath", false, "path", pos1, "time", aniTime - EndAniTime, "easetype", "easeInCubic"));
            iTween.MoveTo(m_RedEffect, iTween.Hash("islocal", true, "movetopath", false, "path", pos2, "time", aniTime - EndAniTime, "easetype", "easeInCubic"));

            iTween.MoveTo(m_GreenEffect, iTween.Hash("islocal", true, "x", max + m_ParticleStartPosx, "time", EndAniTime, "easetype", "easeInCubic",
                "oncompletetarget", gameObject, "oncomplete", "EndGageMoveSuc", "delay", aniTime - EndAniTime));
        }
        else
        {
            iTween.MoveTo(m_GreenEffect, iTween.Hash("islocal", true, "movetopath", false, "path", pos2, "time", aniTime - EndAniTime, "easetype", "easeInCubic"));
            iTween.MoveTo(m_RedEffect, iTween.Hash("islocal", true, "movetopath", false, "path", pos1, "time", aniTime - EndAniTime, "easetype", "easeInCubic"));

            iTween.MoveTo(m_RedEffect, iTween.Hash("islocal", true, "x", max + m_ParticleStartPosx, "time", EndAniTime, "easetype", "easeInCubic",
                "oncompletetarget", gameObject, "oncomplete", "EndGageMoveFail", "delay", aniTime - EndAniTime));
        }

        m_IsGageMoving = true;

        m_EffectIng.SetActive(true);

        SoundController.PlaySound("UI_gathering_cast", true);
    }

    void SetGageInit()      // 게이지 리셋
    {
        iTween.Stop(m_GreenEffect);
        iTween.Stop(m_RedEffect);

        m_GreenEffect.transform.localPosition = new Vector3(m_ParticleStartPosx, 35.0f, 2.0f);
        m_RedEffect.transform.localPosition = new Vector3(m_ParticleStartPosx, -37.0f, 2.0f);

        m_GreenGage.SetDimensions(m_GageStartDimensionsX, 29);
        m_RedGage.SetDimensions(m_GageStartDimensionsX, 29);

        m_EffectIng.SetActive(false);
        m_EffectSuccess.SetActive(false);

        m_SuccessAni.gameObject.SetActive(false);
        m_FailAni.gameObject.SetActive(false);
    }

    void UpdateGage()
    {
        if (m_IsGageMoving)
        {
            m_GreenGage.SetDimensions((int)m_GreenEffect.transform.localPosition.x - m_ParticleStartPosx + m_GageStartDimensionsX, 29);
            m_RedGage.SetDimensions((int)m_RedEffect.transform.localPosition.x - m_ParticleStartPosx + m_GageStartDimensionsX, 29);
        }
    }

    void EndGageMoveSuc()   // 성공시 이펙트 플레이
    {
        SoundController.StopSound("UI_gathering_cast");
        SoundController.PlaySound("UI_intension_success");

        //마지막 이펙트 터치는 곳
        m_SuccessAni.gameObject.SetActive(true);
        m_EffectSuccess.SetActive(true);

        StartCoroutine(EndEnhance(3.0f));
    }

    void EndGageMoveFail()
    {
        SoundController.StopSound("UI_gathering_cast");
        SoundController.PlaySound("UI_intension_fail");

        //마지막 이펙트 터치는 곳  
        m_FailAni.gameObject.SetActive(true);

        StartCoroutine(EndEnhance(3.0f));
    }


    IEnumerator EndEnhance(float waitTime)
    {
        Invoke("GetQuestInfo", 0.5f);

        yield return new WaitForSeconds(waitTime);

        InitScene();
    }

    void InitScene()
    {
        m_IsGageMoving = false;

        SetGageInit();

        if (m_IsFirstInit)
        {
            m_IntroAni.Play("Item_powerup_UI In");
            m_IsFirstInit = false;
        }
        else
        {
            m_IntroAni.Play("Item_powerup_UI Back");
        }
        
        //m_02Panel.SetActive(false);
        m_02Panel.transform.localPosition = m_02PanelFarPos;

        m_ItemBG.color = Constants.GetItemBGRareColorValue(m_SelectItem.itemInfo.rarity);

        if (m_SelectItem.m_level < m_SelectItem.itemInfo.upgradeMax)        
        {
            //===================================

            m_ItemName.text = TextController.GetStringWithId(string.Format("itemName{0}", m_SelectItem.itemInfo.itemID));
            m_ItemName.localSize.Set(0, 0);
            m_ItemName.MakePixelPerfect();
            float size = m_ItemName.width / 2;
           
            m_ItemLevel.text = string.Format("[00ffff]+{0}[-]", m_SelectItem.level);
            m_ItemLevel.MakePixelPerfect();
            
            Vector3 pos = m_ItemLevel.transform.parent.localPosition;
            pos.x = m_ItemName.transform.localPosition.x + size + gap;
            m_ItemLevel.transform.parent.localPosition = pos;

            int crrValue = 0;
            int upValue = 0;

            if (m_SelectItem.itemInfo.effectType1 > 0)
            {
                crrValue = m_SelectItem.effectValue01;
                upValue = Item.GetItemEffectValueWithLevel(m_SelectItem, m_SelectItem.level + 1, 1);

                m_Name01.text = TextController.GetStringWithId(string.Format("combatStat{0}", m_SelectItem.itemInfo.effectType1));
                m_Name01.MakePixelPerfect();
                m_SuccessName01.text = m_Name01.text;
                m_SuccessName01.MakePixelPerfect();
                m_CrrValue01.text = string.Format("+{0}", crrValue);
                m_CrrValue01.MakePixelPerfect();
                m_UpValue01.text = string.Format("{0}", upValue - crrValue);
                m_UpValue01.MakePixelPerfect();
                m_SuccessCrrValue01.text = string.Format("[7eff00]{0}[-]", upValue);
                m_SuccessCrrValue01.MakePixelPerfect();
                m_Text01Root.SetActive(true);
            }
            else
            {
                m_Text01Root.SetActive(false);
                m_SuccessCrrValue01.transform.parent.gameObject.SetActive(false);
            }

            if (m_SelectItem.itemInfo.effectType2 > 0)
            {
                crrValue = m_SelectItem.effectValue02;
                upValue = Item.GetItemEffectValueWithLevel(m_SelectItem, m_SelectItem.level + 1, 2);
               
                m_CrrValue02.text = string.Format("+{0}", crrValue);
                m_CrrValue02.MakePixelPerfect();
                m_UpValue02.text = string.Format("{0}", upValue - crrValue);
                m_UpValue02.MakePixelPerfect();
                m_Name02.text = TextController.GetStringWithId(string.Format("combatStat{0}", m_SelectItem.itemInfo.effectType2));
                m_Name02.MakePixelPerfect();
                m_SuccessName02.text = m_Name02.text;
                m_SuccessName02.MakePixelPerfect();
                m_SuccessCrrValue02.text = string.Format("[7eff00]{0}[-]", upValue);
                m_SuccessCrrValue02.MakePixelPerfect();

                m_Text02Root.SetActive(true);
            }
            else
            {
                m_Text02Root.SetActive(false);
                m_SuccessCrrValue02.transform.parent.gameObject.SetActive(false);
            }

            DItemUpgrade upInfo = null;

            foreach (DItemUpgrade tInfo in GameData.Inst.itemUpgrade)
            {
                if (m_SelectItem.itemInfo.rarity == tInfo.rarity && m_SelectItem.level + 1 == tInfo.upgradeLevel)
                {
                    upInfo = tInfo;
                }
            }
          
            m_SuccessPercent.text = string.Format("{0}% [7eff00](+{1}%)[-]", (int)(upInfo.prob / 10.0f), (m_SelectItem.strengFailCount / 5) * 5);
            m_SpendKina.text = string.Format("{0:#,0}", upInfo.cost);

            m_01Panel.SetActive(true);
            m_04Panel.SetActive(false);
           
            for (int i = 0; i < RareMax; i++)
            {
                m_Stars_01[i].SetActive(m_SelectItem.itemInfo.rarity == i + 1);               
            }
        }
        else
        {
            m_ItemName_04.text = TextController.GetStringWithId(string.Format("itemName{0}", m_SelectItem.itemInfo.itemID));

            m_ItemName_04.MakePixelPerfect();
            float size = m_ItemName_04.width / 2;

            Transform tr = m_ItemName_04.transform.parent.Find("Lv");

            Vector3 pos = tr.localPosition;
            pos.x = m_ItemName.transform.localPosition.x + size + gap;
            tr.localPosition = pos;

            m_01Panel.SetActive(false);
            m_04Panel.SetActive(true);

            for (int i = 0; i < RareMax; i++)
            {
                m_Stars_04[i].SetActive(m_SelectItem.itemInfo.rarity == i + 1);
            }
        }

        SetItemModel();
    }


    public override void BackButton()
    {
        
        if(m_SelectMember != null)
        {
            foreach(KeyValuePair<string , MemberModel> t in UserData.Instance.userModel.members_dic)
            {
                if(t.Value.no == m_SelectMember.no)
                {
                    m_SelectMember = t.Value;
                    break;
                }
            }

            CharacterInfoScene.ModelForInitWithItemRoot(m_SelectMember);  // 케릭터 인포씬 초기 설정 멤버 갱신된 멤버로 재 할당
        }
        
        CharacterInfoScene.InitWithItemRoot();
        SceneController.LoadLevel("Character_Info");
    }


    // 동적 케릭터 모델 관리
   
    [HideInInspector]
    public GameObject m_3DModels = null;
    Dictionary<string, GameObject> m_ModelPrefab = new Dictionary<string, GameObject>();

    void SetItemModel()
    {       
        GameObject prefab = null;
        GameObject model = null;   

        string modelName = GameData.Inst.ItemDefineDic[m_SelectItem.itemInfo.modelID];
        
        if (m_3DModels != null && m_3DModels.name.Equals(modelName))  // 같은 위치 케릭터면 이전 케릭터 재사용
        {
            return;
        }
        else if (m_3DModels != null)
            Destroy(m_3DModels);
       
        if (m_ModelPrefab.ContainsKey(modelName))
            prefab = m_ModelPrefab[modelName];
        else
        {
            prefab = ResourceLoader.Load(string.Format("Prefab/Battle/Weapon/{0}", modelName)) as GameObject;

            if (prefab != null)     // 없는 아이템 예외처리
                m_ModelPrefab.Add(modelName, prefab);
            else
                return;
        }

        model = Instantiate(prefab) as GameObject;
        model.name = modelName;       

        m_3DModels = model;        

        for (int j = 0; j < ItemRoot.childCount; j++)
        {
            if (ItemRoot.GetChild(j).name.Equals(modelName))
            {
                model.transform.parent = ItemRoot.GetChild(j);
                model.transform.localScale = Vector3.one;
                model.transform.localPosition = Vector3.zero;
                model.transform.localRotation = Quaternion.Euler(Vector3.zero);
                ItemRoot.GetChild(j).gameObject.SetActive(true);
                break;
            }
        }
    }
}
